package com.wmh.baseservice.operationaid.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmh.baseservice.common.mybatisplus.structure.LambdaQueryWrapperX;
import com.wmh.baseservice.operationaid.entity.ProductTrafficSource;
import com.wmh.baseservice.operationaid.excel.ProductTrafficSourceExcel;
import com.wmh.baseservice.operationaid.mapper.ProductTrafficSourceMapper;

import com.wmh.baseservice.operationaid.pojo.vo.productTrafficSource.ExponentialField;
import com.wmh.baseservice.operationaid.pojo.vo.productTrafficSource.ProductTrafficSourceReqVO;
import com.wmh.baseservice.operationaid.pojo.vo.productTrafficSource.ProductTrafficSourceRobotCommitReqVO;
import com.wmh.baseservice.operationaid.service.ProductTrafficSourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 谢骏
 * @description 针对表【operation_aid_product_trafficSource(运营助手-商品数据-流量来源)】的数据库操作Service实现
 * @createDate 2023-07-21 11:08:42
 */
@Service
@Slf4j
public class ProductTrafficsourceServiceImpl extends ServiceImpl<ProductTrafficSourceMapper, ProductTrafficSource>
        implements ProductTrafficSourceService {

    @Resource
    private ProductTrafficSourceMapper productTrafficSourceMapper;

    @Override
    public void robotCommitData(ProductTrafficSourceRobotCommitReqVO reqVO) {
        // 获取已存在的数据
        Map<String, ProductTrafficSource> oldEntity = baseMapper.selectList(new LambdaQueryWrapperX<ProductTrafficSource>()
                .eq(ProductTrafficSource::getStoreName, reqVO.getStoreName())
                .eq(ProductTrafficSource::getProductId, reqVO.getProductId())
                .eq(ProductTrafficSource::getDataCycle, reqVO.getDataCycle()))
                .stream().collect(Collectors.toMap(ProductTrafficSource::getTrafficsSource,i-> i));
        log.info("==============================================");
        log.info(reqVO.getExponentialFieldListJson());
        log.info("==============================================");
        List<ExponentialField> nowData = JSON.parseArray(reqVO.getExponentialFieldListJson(), ExponentialField.class);

        List<ProductTrafficSource> saveList = nowData.stream().map(item -> {
            ProductTrafficSource r = oldEntity.get(item.getTrafficsSource());
            if (r != null) {
                clearBaseFields(r);
            }
            r = ProductTrafficSourceRobotCommitReqVO.buildEntity(reqVO, item);
            return r;
        }).collect(Collectors.toList());
        // 一点防重复策略
        saveList = new ArrayList<>(saveList.stream()
                .collect(Collectors.toMap(
                        item -> item.getProductId() + item.getTrafficsSource(),
                        item -> item,
                        (existing, replacement) -> existing
                ))
                .values());
        saveOrUpdateBatch(saveList);
    }

    @Override
    public List<String> getStoreNameList() {
        return baseMapper.selectStoreNameList();
    }

    @Override
    public List<String> getDataCycleList() {
        return baseMapper.selectDataCycleList();
    }


    private void clearBaseFields(ProductTrafficSource entity){
        entity.setCreateTime(null).setUpdateTime(null).setDeleted(null);
    }

    @Override
    public List<ProductTrafficSource> getTrafficsSourceList(ProductTrafficSourceReqVO reqVO) {
        List<String> trafficsSourceList = reqVO.getTrafficsSourceNameListJson() != null ?
                JSON.parseArray(reqVO.getTrafficsSourceNameListJson(),String.class) : null;

        LambdaQueryWrapperX<ProductTrafficSource> wrapper = new LambdaQueryWrapperX<ProductTrafficSource>();

        wrapper.eqIfPresent(ProductTrafficSource::getProductId, reqVO.getProductId());
        wrapper.eq(StrUtil.isNotBlank(reqVO.getStoreName()),ProductTrafficSource::getStoreName, reqVO.getStoreName());
        wrapper.inIfPresent(ProductTrafficSource::getTrafficsSource, trafficsSourceList);
        wrapper.eq(StrUtil.isNotBlank(reqVO.getDataCycle()),ProductTrafficSource::getDataCycle, reqVO.getDataCycle());

        return productTrafficSourceMapper.selectList(wrapper);
    }

    /**
     * 商品流量来源下载为 Excel 表格文件
     */
    @Override
    public void writeExcel(HttpServletResponse response, ProductTrafficSourceReqVO reqVO) {
        List<ProductTrafficSource> productTrafficsSourceList = getTrafficsSourceList(reqVO);
        List<ProductTrafficSourceExcel> data = productTrafficsSourceList.stream()
                .map(pt -> {
                    ProductTrafficSourceExcel pte = new ProductTrafficSourceExcel();

                    BeanUtils.copyProperties(pt, pte);

                    return pte;
                })
                .collect(Collectors.toList());

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        String fileName ;
        try {
            fileName = URLEncoder.encode("fileName", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        try {
            EasyExcel.write(response.getOutputStream(), ProductTrafficSourceExcel.class).sheet("Sheet1").doWrite(data);
        } catch (IOException e) {
            log.error("下载商品流量来源数据异常: {}", e.getMessage());
            throw new RuntimeException(e);
        }
    }
}




